<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.*" %>
<%@ page import="org.json.JSONArray" %>
<%@ page import="org.json.JSONObject" %>

<%
    // 获取订单参数
    Integer userId = (Integer) session.getAttribute("userId");
    if (userId == null) {
        // 将当前URL存储在session中
        String currentUrl = request.getRequestURL().toString();
        String queryString = request.getQueryString();
        if (queryString != null) {
            currentUrl += "?" + queryString;
        }
        session.setAttribute("redirectUrl", currentUrl);
        response.sendRedirect("login.jsp");
        return;
    }
    
    String amountStr = request.getParameter("amount");
    String discountStr = request.getParameter("discount");
    String itemsJson = request.getParameter("items");
    String itemCountStr = request.getParameter("itemCount");
    
    double amount = 0.0;
    double discount = 0.0;
    int itemCount = 0;
    List<Map<String, Object>> items = new ArrayList<>();
    
    try {
        amount = Double.parseDouble(amountStr);
        discount = Double.parseDouble(discountStr);
        itemCount = Integer.parseInt(itemCountStr);
        
        // 解析商品信息
        String decodedItemsJson = java.net.URLDecoder.decode(itemsJson, "UTF-8");
        System.out.println("解析的JSON数据: " + decodedItemsJson);
        
        // 确保JSON数据是一个数组
        String jsonArrayString = decodedItemsJson.startsWith("[") ? decodedItemsJson : "[" + decodedItemsJson + "]";
        JSONArray jsonArray = new JSONArray(jsonArrayString);
        
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Map<String, Object> item = new HashMap<>();
            try {
                if (jsonObject.has("cartId")) {
                    item.put("cartId", jsonObject.getString("cartId"));
                }
                item.put("productId", String.valueOf(jsonObject.getInt("productId")));
                item.put("quantity", String.valueOf(jsonObject.getInt("quantity")));
                item.put("price", jsonObject.getDouble("price"));
                item.put("subtotal", jsonObject.getDouble("subtotal"));
                item.put("name", jsonObject.getString("name"));
                item.put("image", jsonObject.getString("image"));
                items.add(item);
            } catch (Exception e) {
                System.out.println("解析商品数据出错: " + e.getMessage());
                e.printStackTrace();
            }
        }
        
        // 设置到request属性中供JSP使用
        request.setAttribute("amount", amount);
        request.setAttribute("discount", discount);
        request.setAttribute("items", items);
        request.setAttribute("itemCount", itemCount);
        // 将itemsJson重新编码以便在JavaScript中使用
        request.setAttribute("itemsJson", java.net.URLEncoder.encode(jsonArrayString, "UTF-8"));
        
        // 生成订单号
        String orderNumber = "TLL" + System.currentTimeMillis();
        request.setAttribute("orderNumber", orderNumber);
    } catch (Exception e) {
        e.printStackTrace();
    }
%>

<!DOCTYPE html>
<html>
<head>
    <title>淘乐乐 - 订单支付</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script>
        let selectedPayment = 'alipay';
        let orderNumber = '${orderNumber}';
        
        function selectPayment(element, method) {
            // 移除其他选项的选中状态
            document.querySelectorAll('.payment-option').forEach(option => {
                option.classList.remove('selected');
            });
            // 添加当前选项的选中状态
            element.classList.add('selected');
            selectedPayment = method;
        }

        function submitPayment() {
            // 禁用支付按钮
            const payButton = document.querySelector('.pay-button');
            payButton.disabled = true;
            payButton.textContent = '支付处理中...';
            
            // 收集支付数据
            const paymentData = {
                orderNumber: orderNumber,
                amount: ${amount - discount},
                items: JSON.parse(decodeURIComponent('${itemsJson}'))
            };
            
            // 发送支付请求
            fetch('payment/process', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(paymentData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示支付成功对话框
                    showPaymentSuccess();
                } else {
                    throw new Error(data.message || '支付失败');
                }
            })
            .catch(error => {
                console.error('支付失败:', error);
                alert(error.message || '支付失败，请重试');
                // 恢复支付按钮
                payButton.disabled = false;
                payButton.textContent = '立即支付';
            });
        }
        
        function showPaymentSuccess() {
            // 创建模态框
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: white;
                padding: 30px;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                text-align: center;
                z-index: 1000;
            `;
            
            modal.innerHTML = `
                <i class="fas fa-check-circle" style="color: #52c41a; font-size: 48px;"></i>
                <h2 style="margin: 20px 0; color: #333;">支付成功！</h2>
                <p style="color: #666; margin-bottom: 20px;">订单号：${orderNumber}</p>
                <button onclick="window.location.href='my-orders.jsp'" style="
                    background: #ff4d4f;
                    color: white;
                    border: none;
                    padding: 10px 20px;
                    border-radius: 4px;
                    cursor: pointer;
                ">查看订单</button>
            `;
            
            // 创建遮罩
            const overlay = document.createElement('div');
            overlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0,0,0,0.5);
                z-index: 999;
            `;
            
            document.body.appendChild(overlay);
            document.body.appendChild(modal);
            
            // 3秒后自动跳转
            setTimeout(() => {
                window.location.href = 'my-orders.jsp';
            }, 3000);
        }
        
        function startTimer(duration, display) {
            let timer = duration, minutes, seconds;
            let countdown = setInterval(function () {
                minutes = parseInt(timer / 60, 10);
                seconds = parseInt(timer % 60, 10);

                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                display.textContent = minutes + ":" + seconds;

                if (--timer < 0) {
                    clearInterval(countdown);
                    alert("支付超时，请重新下单");
                    window.location.href = "cart.jsp";
                }
            }, 1000);
        }
        
        // 等待DOM加载完成
        window.onload = function() {
            // 启动倒计时
            let fifteenMinutes = 60 * 15,
                display = document.querySelector('#timer');
            startTimer(fifteenMinutes, display);
            
            // 初始化支付方式选择
            document.querySelector('.payment-option.selected').click();
        };
    </script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }
        
        .header {
            background-color: #ff4d4f;
            padding: 15px 0;
            color: white;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 0 15px;
        }
        
        .logo {
            font-size: 24px;
            font-weight: bold;
        }
        
        .main-content {
            display: flex;
            gap: 20px;
            margin: 20px auto;
            max-width: 1000px;
            padding: 0 15px;
        }
        
        .order-details {
            flex: 2;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .payment-section {
            flex: 1;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            position: sticky;
            top: 20px;
            height: fit-content;
        }
        
        .section-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .order-info {
            margin-bottom: 20px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            color: #666;
        }
        
        .price {
            color: #ff4d4f;
            font-size: 24px;
            font-weight: bold;
        }
        
        .payment-methods {
            margin-bottom: 20px;
        }
        
        .payment-option {
            border: 1px solid #ddd;
            padding: 15px;
            margin: 10px 0;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .payment-option:hover {
            border-color: #ff4d4f;
        }
        
        .payment-option.selected {
            border-color: #ff4d4f;
            background-color: #fff1f0;
        }
        
        .payment-option img {
            width: 24px;
            height: 24px;
        }
        
        .pay-button {
            width: 100%;
            padding: 15px;
            background-color: #ff4d4f;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .pay-button:hover {
            background-color: #ff6b6b;
        }
        
        .timer {
            text-align: center;
            margin-top: 15px;
            color: #666;
        }
        
        .timer span {
            color: #ff4d4f;
            font-weight: bold;
        }
        
        .items-list {
            margin-top: 20px;
        }
        
        .item {
            display: flex;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
            align-items: center;
        }
        
        .item-info {
            flex: 1;
        }
        
        .item-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .item-price {
            color: #ff4d4f;
            font-weight: bold;
        }
        
        .item-source {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <div class="logo">淘乐乐 - 订单支付</div>
        </div>
    </div>

    <div class="main-content">
        <div class="order-details">
            <div class="section-title">订单详情</div>
            <div class="order-info">
                <div class="info-row">
                    <span>订单编号：</span>
                    <span>${orderNumber}</span>
                </div>
                <div class="info-row">
                    <span>商品数量：</span>
                    <span>${itemCount}件</span>
                </div>
            </div>

            <div class="items-list">
                <c:forEach var="item" items="${items}">
                    <div class="item">
                        <img src="images/${item.image}" alt="${item.name}" style="width: 50px; height: 50px; object-fit: cover; margin-right: 15px;">
                        <div class="item-info">
                            <div class="item-name">${item.name}</div>
                            <div>数量：${item.quantity}</div>
                            <c:if test="${not empty item.cartId}">
                                <div class="item-source">来自购物车</div>
                            </c:if>
                        </div>
                        <div class="item-price">¥${item.subtotal}</div>
                    </div>
                </c:forEach>
            </div>
        </div>

        <div class="payment-section">
            <div class="section-title">支付信息</div>
            <div class="info-row">
                <span>商品金额</span>
                <span>¥${amount}</span>
            </div>
            <div class="info-row">
                <span>优惠金额</span>
                <span>-¥${discount}</span>
            </div>
            <div class="info-row">
                <span>实付金额</span>
                <span class="price">¥${amount - discount}</span>
            </div>

            <div class="payment-methods">
                <div class="payment-option selected" onclick="selectPayment(this, 'alipay')">
                    <img src="images/alipay.png" alt="支付宝">
                    <span>支付宝</span>
                </div>
                <div class="payment-option" onclick="selectPayment(this, 'wechat')">
                    <img src="images/wechat.png" alt="微信支付">
                    <span>微信支付</span>
                </div>
                <div class="payment-option" onclick="selectPayment(this, 'unionpay')">
                    <img src="images/unionpay.png" alt="银联支付">
                    <span>银联支付</span>
                </div>
            </div>

            <button class="pay-button" onclick="submitPayment()">立即支付</button>
            
            <div class="timer">
                请在 <span id="timer">15:00</span> 内完成支付
            </div>
        </div>
    </div>
</body>
</html> 